package com.example.yaseademo

import android.content.Context
import android.net.TrafficStats
import android.util.Log
import kotlinx.coroutines.*

object NetworkSpeedChecker {
    /*    static long getMobileRxBytes() //获取通过Mobile连接收到的字节总数，不包含WiFi
        static long getMobileRxPackets() //获取Mobile连接收到的数据包总数
        static long getMobileTxBytes() //Mobile发送的总字节数
        static long getMobileTxPackets() //Mobile发送的总数据包数
        static long getTotalRxBytes() //获取总的接受字节数，包含Mobile和WiFi等
        static long getTotalRxPackets() //总的接受数据包数，包含Mobile和WiFi等
        static long getTotalTxBytes() //总的发送字节数，包含Mobile和WiFi等
        static long getTotalTxPackets() //发送的总数据包数，包含Mobile和WiFi等
        static long getUidRxBytes(int uid) //获取某个网络UID的接受字节数，某一个进程的总接收量
        static long getUidTxBytes(int uid) //获取某个网络UID的发送字节数，某一个进程的总发送量*/
    private var job: Job? = null

    private suspend fun getNetSpeedKbs(context: Context, periodSeconds: Long): Long {
        return withContext(Dispatchers.IO) {
            val lastTimeGet = TrafficStats.getUidRxBytes(context.applicationInfo.uid) + TrafficStats.getUidTxBytes(context.applicationInfo.uid)
            Log.d("getNetSpeed", "total:${lastTimeGet} B")
            if (lastTimeGet != TrafficStats.UNSUPPORTED.toLong()) {
                delay(periodSeconds * 1000)
                return@withContext (TrafficStats.getUidRxBytes(context.applicationInfo.uid) + TrafficStats.getUidTxBytes(context.applicationInfo.uid) - lastTimeGet) / periodSeconds
            } else {
                return@withContext TrafficStats.UNSUPPORTED.toLong()
            }
        }
    }

    fun getNetSpeed(context: Context, periodSeconds: Long, getNetSpeedDone: (Long) -> Unit) {
        job = GlobalScope.launch(Dispatchers.Main) {
            while (true) {
                val netSpeed = getNetSpeedKbs(context, periodSeconds)
                getNetSpeedDone(netSpeed)
            }
        }

    }

    fun cancelJob() {
        job?.cancel()
        Log.d("NetworkSpeedChecker","job cancel")
    }
}